layui.use(['form','layer','upload','laydate'],function(){
    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;
    var upload = layui.upload;

    //回显数据
    var request = GetRequest();
    $.get("/user/" + request.id,function (user) {
        console.log(user);
        $("#id").val(user.id);
        $("#loginName").val(user.name);
        $("#mobile").val(user.mobile);
        $("#email").val(user.email);
        //用户角色信息
        $.get("/role",function (data) {

            //TODO  data要处理下

            $.each(data.data,function (i, ele) {
               if (user.roleId == ele.id) {
                   $("#roleId").append('<option selected="selected" value="'+ ele.id +'">'+ ele.name +'</option>');
               } else {
                   $("#roleId").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
               }
            });
            form.render('select');
        });

    });

    //修改用户分类信息
    form.on('submit(edit)', function(data){
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            url: '/user/'+data.id,
            data: data.field,
            type: 'put',
            success: function (data) {
                if(data.code == 200) {
                    top.layer.close(index);
                    top.layer.msg("修改成功！");
                    layer.closeAll("iframe");
                    //刷新父页面
                    parent.location.reload();
                } else {
                    top.layer.close(index);
                    top.layer.msg("修改失败！");
                }
            },
            error:function () {
                top.layer.close(index);
                top.layer.msg("修改失败！");
            }
        });
        return false;
    });

    //获取路径中的参数
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

    //上传头像
    upload.render({
        elem: '.userFaceBtn',
        field: 'uploadFile',//上传文件的名称，要和接口参数名称相同
        url: '/upload/pic',
        done: function(res, index, upload){
            if (res.code === 0) {
                layer.msg(res.msg);
                $("#userFace").attr("src",res.url);
                $("#photo").val(res.url);
            } else {
                layer.msg(res.msg);
            }
        }
    });

});